package net.butfly.bus.server.deploy;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import net.butfly.bus.Constants;
import net.butfly.bus.context.Context;
import net.butfly.bus.server.ServerWrapper;
import net.butfly.bus.util.EnumFactory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.caucho.hessian.io.AbstractSerializerFactory;
import com.caucho.hessian.io.SerializerFactory;
import com.caucho.hessian.server.HessianServlet;

public class HessianEntryPointServlet extends HessianServlet {
	private static final long serialVersionUID = -2493158151789223720L;
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	private SerializerFactory factory = null;

	@Override
	public void init() throws ServletException {
		super.init();
		try {
			logger.info("开始启动EBox.");
			ServerWrapper.register(this.getInitParameter("config-file"));
			logger.info("启动EBox完成");
		} catch (Throwable ex) {
			logger.error("启动EBox失败");
			throw handle(ex);
		}
	}

	public SerializerFactory getSerializerFactory() {
		if (null == factory) {
			factory = super.getSerializerFactory();
			AbstractSerializerFactory af = null;
			try {
				af = (AbstractSerializerFactory) Thread.currentThread().getContextClassLoader()
						.loadClass(Constants.Configuration.ENUM_FACTORY_CLASSNAME).newInstance();
			} catch (Exception ex) {
				af = new EnumFactory();
			}
			factory.addFactory(af);
		}
		return factory;
	}

	public void service(ServletRequest request, ServletResponse response) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		if ("GET".equals(req.getMethod())) {
			this.echo(req, response);
		} else {
			Context.setSourceHost(request.getRemoteAddr());
			try {
				super.service(request, response);
			} catch (Throwable ex) {
				throw handle(ex);
			}
		}
	}

	@Override
	public void destroy() {
		super.destroy();
	}

	private void echo(HttpServletRequest request, ServletResponse response) throws IOException {
		String qs = request.getQueryString();
		ServletOutputStream os = response.getOutputStream();
		os.println("<h1>EBox service alive checking by echo.</h1>");
		os.println("<p>Echo api has beed asked: <span style=\"color: blue;\">" + qs + "<span>.</p>");
		os.println("<p>Echo api has echoed: <span style=\"color: blue;\">" + qs + "<span>.</p>");
		os.flush();
	}

	private ServletException handle(Throwable ex) {
		logger.error("发生", ex);
		return new ServletException(ex);
	}
}
